using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace FirClient.ObjectPool
{
    public class ObjectPool<T> where T : class
    {
        private readonly Stack<T> m_Stack = new Stack<T>();
        private readonly UnityAction<T> m_ActionOnGet;
        private readonly UnityAction<T> m_ActionOnRelease;

        private readonly object objLock = new object();

        public int countAll { get; private set; }
        public int countActive { get { return countAll - countInactive; } }
        public int countInactive { get { return m_Stack.Count; } }

        public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
        {
            m_ActionOnGet = actionOnGet;
            m_ActionOnRelease = actionOnRelease;
        }

        public T Get()
        {
            lock (objLock)
            {
                T element = m_Stack.Pop();
                if (m_ActionOnGet != null)
                    m_ActionOnGet(element);
                return element;
            }
        }

        public void Release(T element)
        {
            lock (objLock)
            {
                if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
                    Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
                if (m_ActionOnRelease != null)
                    m_ActionOnRelease(element);
                m_Stack.Push(element);
            }
        }
    }
}
